/**
 * [地图交互实现类]
 * @author [leixin]
 * @date [2015-04-01]
 * @param {[type]} config [description]
 */
var SearchMap = function(config){
	MapBase.call(this);
	this.config = config;
	this.locationMarker = null;
	this.hits = [];
    this.markers = [];
    this.maxZoomValue = 18;
    this.zoomGapToMaxLevel = 0;
    this.bufferCircle = null;
    this.geolocation = null;
    this.geocoder = null;
    this.placeSearcher = null;
    this.route = null;
    this.segment = null;
};

SearchMap.prototype = new MapBase();
SearchMap.prototype.constructor = SearchMap;

/**
 * [init 加载地图]
 * @param  {[type]} options [description]
 * @return {[type]}         [description]
 */
SearchMap.prototype.init = function(options) {
	this.initialize(options);

	this.addScalePlugin({
		enhance:true
	});

    var that = this;
    this.mapObj.plugin('AMap.Geolocation', function () {
        that.geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: false,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        that.mapObj.addControl(that.geolocation);
    //    AMap.event.addListener(that.geolocation, 'complete', onComplete);//返回定位信息
    //    AMap.event.addListener(that.geolocation, 'error', onError);      //返回定位出错信息
        AMap.event.addListener(that.geolocation, 'complete', options.locateSuccessCb);//返回定位信息
        AMap.event.addListener(that.geolocation, 'error', options.locateErrorCb);      //返回定位出错信息
    });


    //解析定位结果
    function onComplete (data) {
        var str = '<div>定位成功</div>';
        str += '<div>经度：' + data.position.getLng() + '</div>';
        str += '<div>纬度：' + data.position.getLat() + '</div>';
        str += '<div>精度：' + data.accuracy + ' 米</div>';
        str += '<div>是否经过偏移：' + (data.isConverted ? '是' : '否') + '</div>';
        // result.innerHTML = str;
        return str;
    };

    //解析定位错误信息
    function onError (data) {
        var str = '<p>定位失败</p>';
        str += '<p>错误信息：'
        switch(data.info) {
            case 'PERMISSION_DENIED':
                str += '浏览器阻止了定位操作';
                break;
            case 'POSITION_UNAVAILBLE':
                str += '无法获得当前位置';
                break;
            case 'TIMEOUT':
                str += '定位超时';
                break;
            default:
                str += '未知错误';
                break;
        }
        str += '</p>';
     //   result.innerHTML = str;
        alert(str);
    };

    AMap.service(["AMap.Geocoder"], function() { //加载地理编码
        that.geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        //步骤三：通过服务对应的方法回调服务返回结果，本例中通过逆地理编码方法getAddress回调结果
     /*   that.geocoder.getAddress(new AMap.LngLat(112.752686,37.692514), function(status, result){
            //根据服务请求状态处理返回结果
            if(status=='error') {
                alert("服务请求出错啦！ ");
            }
            if(status=='no_data') {
                alert("无数据返回，请换个关键字试试～～");
            }
            else {
                console.log(result);
            }
        });*/
    });
};

/**
 * [clear 清除地图上的所有要素]
 * @return {[type]} [description]
 */
SearchMap.prototype.clear = function() {
  	this.clearCurrentLocation();
    this.clearBufferCircle();
    this.clearResMarkers();

    this.clearRoute();

    this.mapObj.clearInfoWindow();
};

/**
 * [clearCurrentLocation 删除定位要素]
 * @return {[type]} [description]
 */
SearchMap.prototype.clearCurrentLocation = function () {
    if (this.locationMarker) {
        this.locationMarker.setMap(null);
        this.locationMarker = null;
    }
};

/**
 * [clearResMarkers 删除点资源标记]
 * @return {[type]} [description]
 */
SearchMap.prototype.clearResMarkers = function(){
    if(this.markers){
        for(var i = 0 ;i<this.markers.length;i++){
            var marker = this.markers[i];
            marker.setMap(null);
            marker = null;
        }

        this.markers.length = 0;
    }
};

/**
 * [clearBufferCircle 删除圆圈缓冲边界要素]
 * @return {[type]} [description]
 */
SearchMap.prototype.clearBufferCircle = function(){
    if(this.bufferCircle){
        this.bufferCircle.setMap(null);
        this.bufferCircle = null;
    }
};

/**
 * [addLocationMarker 添加定位标记]
 * @param {[type]} x [description]
 * @param {[type]} y [description]
 */
SearchMap.prototype.addLocationMarker = function(x, y) {
    this.clearCurrentLocation();

    this.locationMarker = this.createIconMarker({
    	x:x,
    	y:y,
    	src:"images/locate.png"
    });
    this.locationMarker.setMap(this.mapObj);
    // this.locationMarker.setzIndex(1000);
};

/**
 * [zoomTo 渐进式定位到一点]
 * @param  {[type]} coords [description]
 * @return {[type]}        [description]
 */
SearchMap.prototype.zoomTo = function(coords) {
    var zoom = this.mapObj.getZoom();
    var that = this;
    var jumpTimer = window.setInterval(function (e) {
        if (zoom >= that.maxZoomValue - that.zoomGapToMaxLevel) {         //17 18
            zoom = that.maxZoomValue - that.zoomGapToMaxLevel;
            that.mapObj.setZoomAndCenter(zoom, new AMap.LngLat(coords.longitude, coords.latitude));
            window.clearInterval(jumpTimer);
            jumpTimer = null;
        } else {                //<17
            zoom = zoom + 4;
            if (zoom > that.maxZoomValue - that.zoomGapToMaxLevel) {
                zoom = that.maxZoomValue - that.zoomGapToMaxLevel;
            }
            that.mapObj.setZoomAndCenter(zoom, new AMap.LngLat(coords.longitude, coords.latitude));
        }
    }, 1000);
};

/**
 * [addCircle description]
 * @param {[type]} x      [description]
 * @param {[type]} y      [description]
 * @param {[type]} radius [description]
 */
SearchMap.prototype.addCircle = function(x,y,radius) {
	 var center = window.Converter.transformFromWGSToGCJ({
        lng: x,
        lat: y
    });

    this.bufferCircle = this.createCircle({
    	x:center.lng,
    	y:center.lat,
    	radius:radius
    });

    this.bufferCircle.setMap(this.mapObj);
    this.mapObj.setFitView([this.bufferCircle].concat(this.markers))
};

/**
 * [centerAt 定位在一个点并]
 * @param  {[type]} coords [description]
 * @return {[type]}        [description]
 */
SearchMap.prototype.centerAt = function (coords) {
    this.addLocationMarker(coords.longitude,coords.latitude);
    this.zoomTo(coords);
};

/**
 * [addResMarkers 添加多个资源要素]
 * @param {[type]} features [description]
 */
SearchMap.prototype.addResMarkers = function(features,featureClickCb){
	var that = this;

	for (var i = 0; i < features.length; i++) {
        var object = features[i];
        var facid = object.attributes["FACID"];
        var lnglat = window.Converter.transformFromWGSToGCJ({
            lng: object.geometry.x,
            lat: object.geometry.y
        })
        object.geometry.xg = lnglat.lng;
        object.geometry.yg = lnglat.lat;
        var source = "images/res-" + FacCodeUtil.getResTypeShortCodeByFacType(object.attributes.FACTYPE) + ".png";

        var marker = this.createIconMarker({
        	x:lnglat.lng,
        	y:lnglat.lat,
        	extData:object,
        	offsetX:-13,
        	offsetY:-15,
        	imageWidth:26,
        	imageHeight:31,
        	markerWidth:26,
        	markerHeight:31,
        	src:source
        });

        marker.setMap(this.mapObj);

 		AMap.event.addListener(marker, 'click', function (e) {
            var extData = e.target.getExtData();
            var lnglat = e.lnglat;
            var pixel = e.pixel;

            fnMapClickHandler(pixel.x, pixel.y);
        });

        this.markers.push(marker);
    }

    /**
     * [fnMapClickHandler 地图要素点击消息处理]
     * @param  {[type]} x [description]
     * @param  {[type]} y [description]
     * @return {[type]}   [description]
     */
    function fnMapClickHandler(x, y) {
        var lnglat = that.mapObj.containTolnglat(new AMap.Pixel(x, y));
        var northEast = that.mapObj.containTolnglat(new AMap.Pixel(x + 15, y - 15));
        var southWest = that.mapObj.containTolnglat(new AMap.Pixel(x - 15, y + 15));
        var bounds = new AMap.Bounds(southWest, northEast);

        that.hits.length = 0;
        for (var i = that.markers.length - 1; i >= 0; i--) {
            var circle = that.markers[i];
            var center = circle.getPosition();
            var contain = bounds.contains(center);
            if (contain) {
                that.hits.push(circle);
            }
        }

        if (that.hits.length == 1) {
            openPointInfoWindow(that.hits[0].getExtData(), that.hits[0].getExtData().resCode,
            	that.hits[0].getPosition().getLng(), that.hits[0].getPosition().getLat());
        } else if (that.hits.length > 0) {
            openMultiPointWindow(that.hits, lnglat);
        }
    }

    /**
     * [openPointInfoWindow 在指定位置打开信息窗体]
     * @param  {[type]} extData [description]
     * @param  {[type]} id      [description]
     * @param  {[type]} lon     [description]
     * @param  {[type]} lat     [description]
     * @return {[type]}         [description]
     */
    function openPointInfoWindow(extData, id, lon, lat) {
        function viewPointInfo(e) {
            arguments[0].stopPropagation();
            that.mapObj.clearInfoWindow();

            featureClickCb(extData.attributes,lon,lat);
        }

        var div = document.createElement('div');
        div.style.border = '4px solid rgb(71,71,71)';
        div.style.height = '40px';
        div.style.width = '55px';
        div.style.backgroundColor = 'rgb(71,71,71)';
        div.style.borderRadius = '4px';

        var middleButton = document.createElement('button');
        middleButton.style.border = 'none';
        middleButton.style.height = '40px';
        middleButton.style.width = '55px';
        middleButton.style.backgroundColor = 'rgb(231,232,233)';
        middleButton.style.backgroundImage = 'url(./images/info.png)';
        middleButton.onclick = viewPointInfo;

        div.appendChild(middleButton);
        that.mapObj.clearInfoWindow();

        //实例化信息窗体
        var infoWindow = new AMap.InfoWindow({
            closeWhenClickMap: true,
            isCustom: true,  //使用自定义窗体
            content: div,
            offset: new AMap.Pixel(0, -10)//-113, -140
        });

        infoWindow.setSize(new AMap.Pixel(300, 300));
        infoWindow.open(that.mapObj, new AMap.LngLat(lon, lat));
    }

    /**
     * [openMultiPointWindow description]
     * @param  {[type]} hits   [description]
     * @param  {[type]} lnglat [description]
     * @return {[type]}        [description]
     */
    function openMultiPointWindow(hits, lnglat) {
        var info = [];
        var content = "<ol id='circleList' style='padding:0;list-style:none;border:1px solid black;overflow: auto;max-height:160px;'>";
        for (var i = 0; i < hits.length; i++) {
            var name = (hits[i].getExtData().attributes.FACNAME != null && hits[i].getExtData().attributes.FACNAME != "") ? hits[i].getExtData().attributes.FACNAME : hits[i].getExtData().attributes.FACCODE;
            if (i == hits.length - 1) {
                content += '<li style="padding:2px 4px;">' + name + "</li>";
            } else {
                content += '<li style="padding:2px 4px;border-bottom:1px solid lightgray;">' + name + "</li>";
            }
        }

        content += '</ol>';
        info.push(content);

        that.mapObj.clearInfoWindow();

        var infoWindow = new AMap.InfoWindow({
            closeWhenClickMap: true,
            content: info.join(""),  //使用默认信息窗体框样式，显示信息内容
            size: new AMap.Size(0, 0),
            autoMove:true
        });

        AMap.event.addListener(infoWindow, 'open', function (e) {
            window.setTimeout(function (evt) {
                $('.amap-info-close').hide();
                var circleList = document.getElementById('circleList');
                if (circleList == null) return;
                var lis = circleList.getElementsByTagName('li');
                for (var i = 0; i < lis.length; i++) {
                    var li = lis[i];
                    var id = li.innerHTML;
                    li.onclick = function (e) {
                        e.stopPropagation();
                        var selectedID = e.target.innerHTML;

                        for (var k = 0; k < that.markers.length; k++) {
                            var circle = that.markers[k];
                            var extData = circle.getExtData();
                            var matchName = (extData.attributes.FACNAME != null && extData.attributes.FACNAME != "") ? extData.attributes.FACNAME : extData.attributes.FACCODE;
                            if (matchName != selectedID) {
                                continue;
                            }

                            openPointInfoWindow(extData, extData.attributes.FACNAME, extData.geometry.xg, extData.geometry.yg);

                            break;
                        }
                    }
                }
            }, 200);
        });

        infoWindow.open(that.mapObj, lnglat);
    }
};

//获取当前位置信息
SearchMap.prototype.getCurrentPosition = function() {
    this.geolocation.getCurrentPosition();
};

//监控当前位置并获取当前位置信息
SearchMap.prototype.watchPosition = function (argument) {
    this.geolocation.watchPosition();
};


SearchMap.prototype.addRoute = function(options) {
    this.clearRoute();

    this.route = this.createLine(options);
    this.route.setMap(this.mapObj);
};

SearchMap.prototype.addSegment = function(options) {
    this.clearSegment();

    this.segment = this.createLine(options);
    this.segment.setMap(this.mapObj);
};

SearchMap.prototype.clearRoute = function(first_argument) {
    this.clearSegment();
    this.clearStartMarker();
    this.clearEndMarker();

    if(this.route){
        this.route.setMap(null);
        this.route = null;
    }
};

SearchMap.prototype.clearSegment = function(first_argument) {
    if(this.segment){
        this.segment.setMap(null);
        this.segment = null;
    }
};

SearchMap.prototype.focus = function() {
    if(this.route && this.segment){
        this.mapObj.setFitView([this.route,this.segment]);
    }
};

SearchMap.prototype.addStartMarker = function(x, y) {
    this.clearStartMarker();

    this.startMarker = this.createCircle({
        x:x,
        y:y,
        fillColor:'red',
        strokeColor:'white',
        strokeWeight:2,
        radius:100,
        fillOpacity:1
    });
    this.startMarker.setMap(this.mapObj);
};

SearchMap.prototype.addEndMarker = function(x, y) {
    this.clearEndMarker();

    this.endMarker = this.createCircle({
        x:x,
        y:y,
        fillColor:'green',
        strokeColor:'white',
        strokeWeight:2,
        radius:100,
        fillOpacity:1
    });
    this.endMarker.setMap(this.mapObj);
};

SearchMap.prototype.clearStartMarker = function() {
    if(this.startMarker){
        this.startMarker.setMap(null);
        this.startMarker = null;
    }
};

SearchMap.prototype.clearEndMarker = function() {
    if(this.endMarker){
        this.endMarker.setMap(null);
        this.endMarker = null;
    }
};